package hgz.stu.review.ruijie.config.resolve;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;

import hgz.stu.review.ruijie.enviroment.SkyEngineEnvType;

/**
 * Description: Function Description
 * Copyright: Copyright (c) 2017
 * Company: Ruijie Co., Ltd.
 * Create Time: 2018/8/28
 *
 * @author dell
 */
public abstract class AbstractConfigResolver implements ConfigResolver {

    protected ResourcePatternResolver resourceLoader;

    public AbstractConfigResolver(ResourcePatternResolver resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    @Override
    public List<Resource> resolveRootResource(SkyEngineEnvType skyEngineEnvType) {
        return getResource(skyEngineEnvType,null);
    }

    @Override
    public List<Resource> resolveModuleResource(SkyEngineEnvType skyEngineEnvType, String moduleName) {
        return getResource(skyEngineEnvType,moduleName);
    }

    private List<Resource> getResource(SkyEngineEnvType skyEngineEnvType, String moduleName){
        List<Resource> resourceList = new ArrayList<>();
        String location = buildLocation(skyEngineEnvType,moduleName);
        if(StringUtils.isEmpty(location)){
            return Collections.emptyList();
        }
        try {
            Resource[] resources = resourceLoader.getResources(location);
            if(resources != null){
                Arrays.stream(resources).forEach(resourceList::add);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resourceList;
    }

    abstract String buildLocation(SkyEngineEnvType skyEngineEnvType, String moduleName);
}
